<?php
/**
 * Zend Image Manipulation Module
 *
 * LICENSE
 *
 * This source file is subject to the new BSD license that is bundled
 * with this package in the file LICENSE.txt.

 * @category   Zimm
 * @package    Zimm
 * @copyright  Copyright (c) 2012 Kristoffer Ingemansson
 * @license    New BSD License
 * @version    $Id: Images.php 4 2012-04-14 12:59:16Z kristoffer.ingemansson@gmail.com $
 */

class Zimm_Model_DbTable_Images extends Zend_Db_Table_Abstract
{
    /**
     * The table name.
     *
     * @var string
     */
    protected $_name = 'zimm_images';

    /**
     * Creates an image row and returns its Id.
     *
     * @param string $imagePath
     * @return integer
     */
    public function fetchImageId($imagePath)
    {
        static $stmt = NULL;
        if (!$stmt ) {
            $select = "INSERT INTO `{$this->_name}` (`dataCreatedDate`, `imageHref`) VALUES(NOW(), ?) "
                . "ON DUPLICATE KEY UPDATE `imageId`=LAST_INSERT_ID(`imageId`)";
            $stmt = $this->getAdapter()->prepare($select);
        }

        $stmt->execute(array($imagePath));
        return $this->getAdapter()->lastInsertId();
    }

    /**
     * Fetches an image row object from supplied $imageId.
     *
     * @param integer $imageId
     * @return Zend_Db_Table_Row_Abstract
     */
    public function fetchImage($imageId)
    {
        static $stmt = NULL;
        if (!$stmt) {
            $sql = "UPDATE `{$this->_name}` SET `dataAccessDate`=NOW() WHERE `imageId`=?";
            $stmt = $this->getAdapter()->prepare($sql);
        }

        if ($row = $this->fetchRow('imageId=' . $this->getAdapter()->quote($imageId))) {
            $stmt->execute(array($row->imageId));
        }

        return $row;
    }

    /**
     * Initialize database adapter.
     * Fetches the database parameters from the multidb resource.
     *
     * @return void
     */
    protected function _setupDatabaseAdapter()
    {
        if (!Zend_Registry::isRegistered('Zimm_Model_DbTable.db') || !$this->_db = Zend_Registry::get('Zimm_Model_DbTable.db')) {
            $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
            $multidb = $bootstrap->getPluginResource('multidb');
            Zend_Registry::set('Zimm_Model_DbTable.db', $this->_db = $multidb->getDb('zimm'));
        }
    }
}